package com.dc.es.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class EsConfig {



    @Bean
    public ElasticsearchClient elasticsearchClient (){
        log.info("elasticsearchClient create");
//        final CredentialsProvider credentialsProvider =
//                new BasicCredentialsProvider();
//        credentialsProvider.setCredentials(AuthScope.ANY,
//                new UsernamePasswordCredentials("elastic", "duanchao"));
//
//        RestClientBuilder builder = RestClient.builder(
//                        new HttpHost("192.168.30.151", 9200))
//                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
//                    @Override
//                    public HttpAsyncClientBuilder customizeHttpClient(
//                            HttpAsyncClientBuilder httpClientBuilder) {
//                        return httpClientBuilder
//                                   .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build())
//                                .setDefaultCredentialsProvider(credentialsProvider);
//                    }
//                });
//        RestClient build = builder.build();

        RestClient build = RestClient.builder(HttpHost.create("http://192.168.30.151:9200"))
                .setDefaultHeaders(new Header[]{ new BasicHeader("Authorization", "ApiKey " +
                        "bWF3czNwQUJYX3l4Um9mb0MxcEo6OGtTajRoV3RRenFzT3dRZlRWSUlmdw==")})
                .build();
// 新版本已经废弃
//        RestHighLevelClient hlrc = new RestHighLevelClientBuilder(build)
//                .setApiCompatibilityMode(true)
//                .build();




        RestClientTransport restClientTransport = new RestClientTransport(build,new JacksonJsonpMapper());
        return  new ElasticsearchClient(restClientTransport);
    }
}
